﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.ServiceModel;
using System.Text;
using Castle.Core;
using Castle.Core.Configuration;
using Castle.MicroKernel;

namespace ilanver.WcfClient.Castle
{
    public class WcfSessionFacility : IFacility
    {
        public const string ManageWcfSessionsKey = "ManageWcfSessions";

        public void Init(IKernel kernel, IConfiguration facilityConfig)
        {
            kernel.ComponentDestroyed += new ComponentInstanceDelegate(kernel_ComponentDestroyed);
        }

        void kernel_ComponentDestroyed(ComponentModel model, object instance)
        {
            bool shouldManage = false;
            object value = model.ExtendedProperties[ManageWcfSessionsKey];

            if (value != null)
            {
                shouldManage = (bool)value;
            }

            if (!shouldManage)
                return;

            ICommunicationObject communicationObject = instance as ICommunicationObject;

            if (communicationObject != null)
            {
                try
                {
                    if (communicationObject.State != CommunicationState.Faulted)
                    {
                        communicationObject.Close();
                    }
                    else
                    {
                        communicationObject.Abort();
                    }
                }
                catch (CommunicationException)
                {
                    communicationObject.Abort();
                }
                catch (System.TimeoutException)
                {
                    communicationObject.Abort();
                }
                catch (Exception)
                {
                    communicationObject.Abort();
                    throw;
                }
            }
        }

        public void Terminate() { }
    }
}
